package com.sjgtw.cloud.system.controller;

import com.sjgtw.cloud.common.core.constant.UserConstants;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.controller.BaseController;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.log.annotation.Log;
import com.sjgtw.cloud.common.log.enums.BusinessType;
import com.sjgtw.cloud.common.security.annotation.PreAuthorize;
import com.sjgtw.cloud.system.api.domain.SysDept;
import com.sjgtw.cloud.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Iterator;
import java.util.List;

/**
 * <p>Title:部门管理</p>
 * <p>Description: </p>
 * @author Admin
 * @date 2020-7-4
 */
@Api(value = "部门管理",tags = {"部门管理接口"}) 
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;

    /**
	 * <p>Title: 获取部门列表--不分页</p>
	 * <p>Description: </p>
	 * @param dept
	 * @return
	 */
    @ApiOperation("获取部门列表--不分页")
    @PreAuthorize(hasPermi = "system:dept:list")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

	/**
	 * <p>Title: 获取部门列表--不分页</p>
	 * <p>Description: </p>
	 * @param dept
	 * @return
	 */
	@ApiOperation("获取部门列表--不分页 无权限")
	@GetMapping("/listAll")
	public AjaxResult listALL(SysDept dept)
	{
		List<SysDept> depts = deptService.selectDeptListAll(dept);
		return AjaxResult.success(depts);
	}

    /**
	 * <p>Title: 查询部门列表（排除节点）</p>
	 * <p>Description: </p>
	 * @param deptId
	 * @return
	 */
	@ApiOperation("查询部门列表（排除节点）")
	@ApiImplicitParam(name = "deptId", value = "部门ID", required = false, dataType = "Long", paramType = "path")
	@PreAuthorize(hasPermi = "system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext())
        {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
	 * <p>Title: 根据部门ID获取部门信息</p>
	 * <p>Description: </p>
	 * @param deptId
	 * @return
	 */
	@ApiOperation("根据部门ID获取部门信息")
	@ApiImplicitParam(name = "deptId", value = "部门ID", required = true, dataType = "Long", paramType = "path")
    @PreAuthorize(hasPermi = "system:dept:query")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

	/**
	 * <p>Title: 根据部门ID获取部门信息</p>
	 * <p>Description: </p>
	 * @param deptId
	 * @return
	 */
	@ApiOperation("根据部门ID获取部门信息")
	@ApiImplicitParam(name = "deptId", value = "部门ID", required = true, dataType = "Long", paramType = "path")
	@GetMapping(value = "/deptId/{deptId}")
	public AjaxResult deptId(@PathVariable Long deptId)
	{
		return AjaxResult.success(deptService.selectDeptById(deptId));
	}
	
	/**
	* <p>Title: 返回离部门ID上级最近的某个部门类型的部门对象</p>
	* <p>Description: </p>
	* @return
	*/
	@ApiOperation("返回离部门ID上级最近的某个部门类型的部门对象")
    @GetMapping("/getpartypedept")
	public AjaxResult findfuDeptByIdType(SysDept dept)
	{
		SysDept deptNew = deptService.selectDeptById(dept.getDeptId());
		dept.setAncestors(deptNew.getAncestors()+","+dept.getDeptId());
		return AjaxResult.success(deptService.findfuDeptByIdType(dept));
	}

	/**
	 * <p>Title: 默认数据权限--获取部门下拉树列表</p>
	 * <p>Description: </p>
	 * @param dept
	 * @return
	 */
	@ApiOperation("默认数据权限--获取部门下拉树所有数据列表")
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

	/**
	 * <p>Title: 加载对应角色部门列表树</p>
	 * <p>Description: </p>
	 * @param roleId
	 * @return
	 */
	@ApiOperation("加载对应角色部门列表树")
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * <p>Title: 新增部门</p>
     * <p>Description: </p>
     * @param dept
     * @return
     */
	@ApiOperation("新增部门")
    @PreAuthorize(hasPermi = "system:dept:add")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在！");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

	/**
	 * <p>Title: 修改部门</p>
	 * <p>Description: </p>
	 * @param dept
	 * @return
	 */
	@ApiOperation("修改部门")
    @PreAuthorize(hasPermi = "system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在！");
        }
        else if (dept.getParentId().equals(dept.getDeptId()))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，父级部门不能选自己！");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0)
        {
            return AjaxResult.error("修改失败，请先停用该部门下的所有子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

	/**
	 * <p>Title: 删除部门</p>
	 * <p>Description: </p>
	 * @param deptId
	 * @return
	 */
	@ApiOperation("删除部门")
    @PreAuthorize(hasPermi = "system:dept:remove")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.error("删除失败，该部门下还有子部门！");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.error("删除失败，该部门下还有绑定用户！");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }
}
